<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Trans\Common\PreAuthRevokeService;
use JLPay\Models\Trans\Common\PreAuthRevokeRequest;
use JLPay\Models\Trans\Common\PreAuthRevokeResponse;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 交易 - Common预授权撤销功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

// =================== 数据构建函数 =====================
/**
 * 构建预授权撤销请求
 */
function buildPreAuthRevokeRequest(): PreAuthRevokeRequest
{
    $request = new PreAuthRevokeRequest();
    
    // 设置请求参数
    $request->setMchId("849584358120018")
        ->setTermNo("60131234")
        ->setPayType("wxpay")
        ->setOutTradeNo("ld" . date("YmdHis") . rand(1000, 9999))
        ->setOriOutTradeNo("ld201911023465529")
        ->setOriTransactionId("123456789012345678")
        ->setGuaranteeAuthCode("123456789012345678")
        ->setTotalFee("100")
        ->setRemark("预授权撤销测试")
        ->setDeviceInfo("60131234")
        ->setMchCreateIp("123.12.12.123")
        ->setTransAddress("北京市朝阳区")
        ->setAreaCode("110105")
        ->setLongitude("116.078631")
        ->setLatitude("39.71274");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 预授权撤销示例
 */
function preAuthRevokeDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行预授权撤销示例");
    
    // 创建配置对象和预授权撤销服务
    $config = createConfig();
    $preAuthRevokeService = new PreAuthRevokeService($config);
    
    // 创建预授权撤销请求
    $request = buildPreAuthRevokeRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $preAuthRevokeService, 
        $request, 
        "预授权撤销",
        function($service, $request) {
            return $service->preAuthRevoke($request);
        }
    );
    
    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
    
    $logger->info("预授权撤销示例执行完毕");
}

// =================== 主程序 =====================
$logger = Logger::getInstance();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 预授权撤销示例 开始 =====");
$logger->info("=" . str_repeat("=", 50));

preAuthRevokeDemo();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 预授权撤销示例执行完毕 =====");
$logger->info("=" . str_repeat("=", 50)); 